# -*- coding: utf-8 -*-
import datetime

from flask import Blueprint, render_template, request, url_for, redirect, jsonify

from application import db
from common.libs.UserSerivice import UserService
from web.models.AppAccessLog import AppAccessLog
from web.models.user import User

route_account = Blueprint('account_page', __name__)


@route_account.route("/index")
def index():
    user_list = User.query.all()
    context = {'list': user_list}
    return render_template("account/index.html", **context)


@route_account.route("/info")
def info():
    # 获取到要查看详情的用户id
    req = request.args
    uid = int(req.get("id", 0))
    reback_url = url_for('account_page.index')
    if uid < 1:
        return redirect(reback_url)
    user = User.query.filter_by(uid=uid).first()
    if not info:
        return redirect(reback_url)
    context = {"info": user}
    access_list = AppAccessLog.query.filter_by(uid=user.uid).all()
    context["access_list"] = access_list
    return render_template("account/info.html", **context)


@route_account.route("/set", methods=["GET", "POST"])
def set():
    # if request.method == 'GET':
    #     req = request.args
    #     uid = int(req.get("id", 0))
    #     if uid:
    #         user = User.query.filter_by(uid=uid).first()
    #         context = {'info': user}
    #         return render_template("account/set.html", **context)
    if request.method == "GET":
        context = {}
        req = request.args
        uid = int(req.get("id", 0))
        info = None
        if uid:
            info = User.query.filter_by(uid=uid).first()
        context["info"] = info
        return render_template("account/set.html", **context)
    req = request.values
    nickname = req["nickname"] if "nickname" in req else ""
    mobile = req["mobile"] if "mobile" in req else ""
    email = req["email"] if "email" in req else ""
    login_name = req["login_name"] if "login_name" in req else ""
    login_pwd = req["login_pwd"] if "login_pwd" in req else ""
    id = req["id"] if "id" in req else 0
    # 2.1 检验账号是否已经注册(新增)
    resp = {"code": 200, "msg": "操作成功", "data": {}}
    # 验证登录名是否被注册 在添加账号时，User.login_name == login_name,但是User.uid != id才会成立
    # 修改： 登录名：hongfei   uid ：1
    has_in = User.query.filter(User.login_name == login_name, User.uid != id).first()
    if has_in:
        resp["code"] = -1
        resp["msg"] = "该登录名已经存在，请换一个试一试 "
        return jsonify(resp)
    # 2.2 依据新增或者修改，构建好要提交的用户信息
    # 编辑or添加账号？
    user_info = User.query.filter_by(uid=id).first()
    if user_info:  # 能拿到就是编辑、修改请求
        # 如果admin账号，不允许修改
        if user_info and user_info.uid == 1:
            resp["code"] = -1
            resp["msg"] = "该用户是admin账号，不允许修改编辑 "
            return jsonify(resp)
        model_user = user_info
    else:  # 拿不到就是新增账号请求
        model_user = User()  # 新建一个User实例
        model_user.login_salt = UserService.genSalt(16)  # 新增用户时，会自动产生一个加盐数据
        model_user.created_time = datetime.datetime.now()
    # 2.3不管是新增，还是修改，共同操作的代码，更新到数据库中
    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    if login_pwd != '******':  # 表示修改了密码 重新生成密码保存，要结合前端的密码默认值比较
        model_user.login_pwd = UserService.genPwd(login_pwd, model_user.login_salt)
    model_user.updated_time = datetime.datetime.now()
    db.session.add(model_user)
    db.session.commit()
    return jsonify(resp)

@route_account.route("/ops", methods=["POST"])
def ops():
    if request.method == "POST":
        resp = {"code": 200, "msg": "操作成功", "data": {}}
        req = request.values
        act = req["act"] if "act" in req else ""
        id = req["id"] if "id" in req else 0
        print('获取到的数据:', act, id)
        if act not in ["remove", "recover"]:
            resp["code"] = -1
            resp["msg"] = "操作有误"
            return jsonify(resp)
        if not id:
            resp["code"] = -1
            resp["msg"] = "请选择要操作的账号"
            return jsonify(resp)
        user_info = User.query.filter_by(uid=id).first()
        if not user_info:
            resp["code"] = -1
            resp["msg"] = "指定账号不存在"
            return jsonify(resp)
        if user_info and user_info.uid == 1:
            resp["code"] = -1
            resp["msg"] = "该用户是admin账号，不允许修改编辑 "
            return jsonify(resp)
        if act == "remove":
            user_info.status = 0  # 删除状态
        elif act == "recover":  # 变成不删除状态
            user_info.status = 1
            user_info.updated_time = datetime.datetime.now()
        db.session.add(user_info)
        db.session.commit()
        return jsonify(resp)

    'flask-sqlacodegen mysql://root:5wojiaoyujida@127.0.0.1/food_db --tables app_access_log --outfile "web/models/AppAccessLog.py" --flask'